package com.miukoo.aikao.admin.config;

import com.miukoo.aikao.admin.security.JtiAuthenticationFilter;
import com.miukoo.aikao.admin.security.SecurityLogoutSuccessHandler;
import com.miukoo.aikao.admin.security.SecurityUserLoginHandler;
import com.miukoo.aikao.admin.security.SysUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @Author miukoo<miukoo@126.com>
 * @Date 2020/11/20  
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    SysUserDetailsService sysUserDetailsService;
    @Autowired
    SecurityUserLoginHandler securityUserLoginHandler;
    @Autowired
    JtiAuthenticationFilter jtiAuthenticationFilter;
    @Autowired
    SecurityLogoutSuccessHandler securityLogoutSuccessHandler;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义登录身份认证组件
        auth.userDetailsService(sysUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 登出
        http.logout().logoutUrl("/user/logout").logoutSuccessUrl("/index.html").logoutSuccessHandler(securityLogoutSuccessHandler);
        // 登录
        http.cors().and().csrf().disable()
                .formLogin().passwordParameter("password")
                .usernameParameter("username")
                .loginPage("/index.html")
                .loginProcessingUrl("/user/login")
                .successHandler(securityUserLoginHandler)
                .failureHandler(securityUserLoginHandler);
        // 资源过滤
        http.authorizeRequests()
                .antMatchers("/metadata/sys/v1/reg","/index.html","/css/**","/js/**","/favicon.ico","/img/**","/fonts/**","/doc.html","/webjars/**","/swagger-resources/**","/*.js","/v2/**").permitAll()
                // 测试用资源，需要验证了的用户才能访问
                .antMatchers("/**").authenticated()
                // 其他都放行了
                .anyRequest().permitAll()
                .and()
                // 不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
        // 权限过滤
        http.addFilterBefore(jtiAuthenticationFilter, HeaderWriterFilter.class);
    }

    /**
     * 放行跨域请求
     * @return
     */
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration.applyPermitDefaultValues());
        return source;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}
